import { initM7WebPhone } from '../../../utils/webphoneSdk/webPhoneSdk'
import * as globalTypes from '../../mutation-types'
import * as types from './mutation-types'
import { MessageBox } from 'element-ui'
let webapp

export const initWebRtc = ({commit, state, rootState, dispatch}, config) => {
  let account = rootState.session.account
  var ishttps = 'https:' == document.location.protocol ? true : false
  if (!account.isOpenPlanTreasure) {
    return
  }
  if (!ishttps) {
    MessageBox.alert('您的账号可能存在以下原因，导致软电话条未连接不能进行外呼：1、当前页面为http环境，需切换到https环境下才可以外呼2、当前浏览器版本太低，需升级浏览器版本或重新下载浏览器', '提示', {
      confirmButtonText: '确定'
    })
    return
  }
  commit(types.SET_AUTO_SHOW_ANSWER, true)
  if (webapp) {
    webapp.init(config)
  }
  const qhbUrl = rootState.platform_urls && rootState.platform_urls.qhbUrl
  config.qhbUrl = qhbUrl
  webapp = new initM7WebPhone(config)
  setTimeout(function(){
    commit(globalTypes.SET_INFO, 'message.in_registration')
  }, 0)
  webapp.onMessage(function (msg) {
    // rtc 事件监测
    console.log(msg)
    if (msg === 'incomingcall') {
      var ringingTone = document.getElementById('webrtc_calleering')
      if (ringingTone) {
        ringingTone.play()
      }
      if (state.autoAnswer) {
        webapp.Outbound()
      } else {
        commit(types.SET_SHOW_ANSWER, true)
      }
    } else if (msg === 'hangup') {
      // eslint-disable-next-line camelcase
      var webrtc_hangup = document.getElementById('webrtc_hangup')
      webrtc_hangup.play()
      commit(types.SET_SHOW_ANSWER, false)
    } else if (msg === 'no_webrtc') {
      MessageBox.alert('您的账号可能存在以下原因，导致软电话条未连接不能进行外呼：1、当前页面为http环境，需切换到https环境下才可以外呼2、当前浏览器版本太低，需升级浏览器版本或重新下载浏览器', '提示', {
        confirmButtonText: '确定'
      })
    }
  })
  webapp.onError(function (event) {
    if (event.type === 'webrtc' && event.error && event.error.name === 'NotAllowedError') {
      commit(globalTypes.SET_ERROR, '禁止使用麦克风后您将不能接听电话，建议您开启麦克风权限！')
    }
  })
}

export const destroyWebrtc = ({commit, state, rootState, dispatch}, config) => {
  if (webapp) {
    webapp.destroy()
  }
}

export const Answer = ({commit, state, rootState, dispatch}, config) => {
  if (webapp) {
    webapp.Outbound()
    commit(types.SET_SHOW_ANSWER, false)
  }
}

export const Hangup = ({commit, state, rootState, dispatch}, config) => {
  if (webapp) {
    webapp.doHangup()
    commit(types.SET_SHOW_ANSWER, false)
  }
}

